<?php
namespace app\common\model;
use app\common\service\Config;
use app\common\service\WxPublic;
use think\Model;
use think\model\concern\SoftDelete;

class WechatSendMsgLogsModel extends BaseModel
{
    use SoftDelete;
    protected $table = 'wechat_send_msg_logs';

    public static $fields_type = [
        ['name'=>'普通消息'],
        ['name'=>'开始答题','temp_msg'=>[
            'params'=>[
                "touser"=>['name'=>'接收者openid','var'=>'openid'],
                "template_id"=>['name'=>'模板ID','value'=>'QkmWg2hmy4dBTkFFgvCdDl8QTH1OM8qL57iH_new3lw'],
                "url"=>['name'=>'模板跳转链接（海外帐号没有跳转能力）','var'=>'url'],
//                "miniprogram"=>['name'=>'跳小程序所需数据，不需跳小程序可不用传该数据','params'=>[
//                    "appid"=>['name'=>'所需跳转到的小程序appid（该小程序appid必须与发模板消息的公众号是绑定关联关系，暂不支持小游戏）','var'=>'appid'],
//                    "pagepath"=>['name'=>'所需跳转到小程序的具体页面路径，支持带参数,（示例index?foo=bar），要求该小程序已发布，暂不支持小游戏','var'=>'pagepath'],
//                ]],
                "data"=>['name'=>'模板数据','params'=>[
                    "first"=>["name"=>"支付信息表述","value"=>'问答服务付款标题','color'=>"#000000"],
                    "keyword1"=>["name"=>"订单号","method_name"=>'no','color'=>"#000000"],
                    "keyword2"=>["name"=>"商品名","method_name"=>'name','color'=>"#000000"],
                    "keyword3"=>["name"=>"支付金额","method_name"=>'money','color'=>"#000000"],
                    "keyword4"=>["name"=>"购买时间","method_name"=>'create_time','color'=>"#000000"],
                    "remark"=>["name"=>'我是remark',"value"=>'点击进行处理','color'=>"#ff0000"],
                ]],
                "color"=>['name'=>'模板内容字体颜色，不填默认为黑色','value'=>"#000000"]
            ]
        ]],
        ['name'=>'答题异常'],
        ['name'=>'问答结果','temp_msg'=>[
            'params'=>[
                "touser"=>['name'=>'接收者openid','var'=>'openid'],
                "template_id"=>['name'=>'模板ID','value'=>'TmQ35T_VnBjoW7AbknHfIZFTfDXJEAPayZKkEkkmIvc'],
                "url"=>['name'=>'测评报告通知','var'=>'url'],
                "data"=>['name'=>'模板数据','params'=>[
                    "first"=>["value"=>'测评报告通知','color'=>"#000000"],
                    "keyword1"=>["value"=>'测评报告','color'=>"#000000"],
                    "keyword2"=>["method_name"=>'create_time','color'=>"#000000"],
                    "remark"=>["name"=>'我是remark',"value"=>'点击查看详细的测评报告','color'=>"#ff0000"],
                ]],
                "color"=>['name'=>'模板内容字体颜色，不填默认为黑色','value'=>"#000000"]
            ]
        ]],
    ];
    public static $fields_m_type = [
        ['name'=>'文本消息','type'=>'text'],
    ];

    //给用户发送消息
    public static function sendUserMsg(Model $obj_model,$type,$openid,array $input_data = [])
    {
        $type_info = self::getPropInfo('fields_type',$type);
        //微信号id
        $og_id = $input_data['og_id']??Config::wechat('wx_mch','og_id');
        $m_type = empty($input_data['m_type']) ? 0 : $input_data['m_type']; //消息类型

        $msg_type = self::getPropInfo('fields_m_type',$m_type,'type');
        try{
            if(isset($type_info['temp_msg'])){  //模板消息
                $msg_params = $type_info['temp_msg']['params'];
                $temp_data = [];
                foreach ($msg_params as $key=>$vo) {
                    $temp_data[$key] = self::handleTempMsgContent($obj_model,$type,$openid,$vo,$input_data);
                }
                $content = json_encode($temp_data);
                $send_result_info = WxPublic::sendTemplateMsg($temp_data);
//                dump($msg_data);exit;
            }else{ //直接发送消息
                $content = $obj_model->getWxMsgContent($type);
                $send_result_info = WxPublic::sendMsg($openid,$content,$msg_type);
            }
        }catch (\Exception $e){
            $send_result_info = $e->getMessage();
        }
        $model = new self();
        $model->setAttrs([
            'type' =>$type,
            'm_type' =>$m_type,
            'cond_id' =>$obj_model['id'],
            'og_id' =>$og_id,
            'openid' =>$openid,
            'content' =>$content,
            'send_result' => is_array($send_result_info) ? json_encode($send_result_info) : $send_result_info,
        ]);
        $model->save();
    }


    //处理模板消息内容
    private static function handleTempMsgContent(Model $obj_model,$type,$openid,array $array,$origin_data)
    {
        $info = "";
        if(isset($array['value'])){ //设置固定值
            $info = $array['value'];
        }elseif(isset($array['params'])){
            $second_data = [];
            foreach ($array['params'] as $key=>$vo){
                if(isset($vo['color'])){
                    $info = [];
                    $info['value'] = self::handleTempMsgContent($obj_model,$type,$openid,$vo,$origin_data);
                    $info['color'] = $vo['color'];
                }else{
                    $info = self::handleTempMsgContent($obj_model,$type,$openid,$vo,$origin_data);

                }
                $second_data[$key] = $info;
            }
            return $second_data;
        }elseif(isset($array['method_name'])){
            $info = $obj_model->getTempMsgContent($array['method_name']);
        }else{
            $var = $array['var'];
            if(!isset($$var)){
                $info = $origin_data[$var]??"";
            }else{
                $info = $$var;
            }
        }
        return $info;
    }


}